<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    body {
      height: 5000px;
      background: #000;
    }

    canvas {
      width: 115vw;
      position: fixed;
      margin-top: -10vh;
    }
  </style>
  <body>
    <div>
      <canvas class="airpod" />
    </div>
    <script>
      const picTotal = 64;
      const html = document.documentElement;
      const canvas = document.querySelector(".airpod");
      const context = canvas.getContext("2d");
      const clientWidth = document.documentElement.clientWidth;
      const imgList = [];
      const airpodImg = (index) => {
        if (index < 10) {
          return `https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/hero/large/000${index}.png`;
        } else {
          return `https://www.apple.com.cn/105/media/us/airpods-pro/2022/d2deeb8e-83eb-48ea-9721-f567cf0fffa8/anim/hero/large/00${index}.png`;
        }
      };

      const loadEvent = () => {
        for (let i = 0; i < picTotal; i++) {
          const img = new Image();
          img.src = airpodImg(i);
          imgList.push(img);
        }
      };

      const img = new Image();
      img.src = airpodImg(1);
      canvas.width = clientWidth;
      canvas.height = 850;
      img.onload = function () {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(img, 0, 0);
      };

      const updateEvent = (index) => {
        if (index <= Number(picTotal + 1)) {
          const img = imgList[index + 1];
        } else {
          const img = imgList[index];
        }
        context.clearRect(0, 0, canvas.width, canvas.height);
        img.src = airpodImg(index);
        context.drawImage(img, 0, 0);
      };

      window.addEventListener("scroll", () => {
        const scrollTop = html.scrollTop;
        const maxNum = html.scrollHeight - window.innerHeight;
        const val = scrollTop / maxNum;
        const index = Math.min(picTotal - 1, Math.ceil(val * picTotal));
        requestAnimationFrame(() => updateEvent(index + 1));
      });

      window.onload = loadEvent();
    </script>
  </body>
</html>
